package com.zjitc.backend_shop.security;

import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjitc.backend_shop.utils.APIResponse;
import com.zjitc.backend_shop.utils.JwtUtils;
import com.zjitc.backend_shop.utils.Token;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/*
    @author： 尤安托
    @date： 2025/4/12 15:04
*/
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        APIResponse apiResponse = new APIResponse();
        response.setContentType("application/json;charset=UTF-8");
        apiResponse.setData(new Token());
        String token = JwtUtils.generateToken(authentication.getName());
        apiResponse.APIResponseOK(0, "登录成功", new Token(token));
        response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
    }
}
